﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace BankSite.Account
{
    public partial class CustomLogin : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            InitializeComponent();
        }

        private bool ValidateUser(string userName, string passWord)
        {
            SqlConnection conn;
            SqlCommand cmd;
            string lookupPassword = null;
            long clientId = 0;

            // Check for invalid userName.
            // userName must not be null and must be between 1 and 15 characters.
            if ((null == userName) || (0 == userName.Length) || (userName.Length > 15))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of userName failed.");
                return false;
            }

            // Check for invalid passWord.
            // passWord must not be null and must be between 1 and 25 characters.
            if ((null == passWord) || (0 == passWord.Length) || (passWord.Length > 25))
            {
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Input validation of passWord failed.");
                return false;
            }

            using(var context = new BankBaseEntities())
            {
                var klienci = context.Klienci.Where(u => u.login == userName);
                Klienci klient = klienci.First();// lookupPassword
                lookupPassword = klient.haslo;
                clientId = klient.id;
            }



            //try
            //{
            //    // Consult with your SQL Server administrator for an appropriate connection
            //    // string to use to connect to your local SQL Server.
            //    //conn = new SqlConnection("server=localhost;Integrated Security=SSPI;database=BANK_BASE");
            //    conn = new SqlConnection(ConfigurationManager.ConnectionStrings["BANK_BASEConnectionString"].ConnectionString);
            //    conn.Open();

            //    // Create SqlCommand to select pwd field from users table given supplied userName.
            //    cmd = new SqlCommand("Select haslo from Klienci where login=@userName", conn);
            //    cmd.Parameters.Add("@userName", SqlDbType.VarChar, 25);
            //    cmd.Parameters["@userName"].Value = userName;

            //    // Execute command and fetch pwd field into lookupPassword string.
            //    lookupPassword = (string)cmd.ExecuteScalar();

            //    // Cleanup command and connection objects.
            //    cmd.Dispose();
            //    conn.Dispose();
            //}
            //catch (Exception ex)
            //{
            //    // Add error handling here for debugging.
            //    // This error message should not be sent back to the caller.
            //    System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
            //}

            // If no password found, return false.
            if (null == lookupPassword)
            {
                // You could write failed login attempts here to event log for additional security.
                return false;
            }

            // Compare lookupPassword and input passWord, using a case-sensitive comparison.
            return (0 == string.Compare(lookupPassword, passWord, false));

        }

        private void cmdLogin_ServerClick(object sender, System.EventArgs e)
        {
            if (ValidateUser(txtUserName.Value, txtUserPass.Value))
            {
                FormsAuthenticationTicket tkt;
                string cookiestr;
                HttpCookie ck;
                tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
          DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, "your custom data");
                cookiestr = FormsAuthentication.Encrypt(tkt);
                ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
                if (chkPersistCookie.Checked)
                    ck.Expires = tkt.Expiration;
                ck.Path = FormsAuthentication.FormsCookiePath;
                Response.Cookies.Add(ck);

                string strRedirect;
                strRedirect = Request["ReturnUrl"];
                if (strRedirect == null)
                    strRedirect = "default.aspx";
                Response.Redirect(strRedirect, true);
            }
            else
                Response.Redirect("logon.aspx", true);
        }

    }
}